using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Windows.Forms;

namespace AutoUpdater
{
    /// <summary>
    /// 系统兼容性辅助类，处理不同Windows版本的兼容性问题
    /// </summary>
    public static class CompatibilityHelper
    {
        [DllImport("kernel32.dll")]
        private static extern bool IsWow64Process(IntPtr hProcess, out bool lpSystemInfo);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetProcessDEPPolicy(uint dwFlags);

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges,
            ref TokPriv1Luid NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength);

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out long lpLuid);

        private const uint TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        private const uint TOKEN_QUERY = 0x00000008;
        private const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        private const uint SE_PRIVILEGE_ENABLED = 0x00000002;

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        private struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public uint Attr;
        }

        /// <summary>
        /// 配置安全协议，兼容不同Windows版本
        /// </summary>
        public static void ConfigureSecurityProtocols()
        {
            try
            {
                // 启用TLS 1.0, 1.1, 1.2, 1.3以兼容现代服务器
                System.Net.ServicePointManager.SecurityProtocol = 
                    System.Net.SecurityProtocolType.Tls | 
                    System.Net.SecurityProtocolType.Tls11 | 
                    System.Net.SecurityProtocolType.Tls12 |
                    (System.Net.SecurityProtocolType)3072; // Tls13

                // 启用证书吊销检查
                System.Net.ServicePointManager.CheckCertificateRevocationList = true;
            }
            catch (Exception ex)
            {
                Logger.Warn($"配置安全协议失败（可能是在旧系统上）: {ex.Message}");
            }
        }

        /// <summary>
        /// 确保程序以管理员权限运行
        /// </summary>
        /// <returns>是否拥有管理员权限</returns>
        public static bool EnsureAdminRights()
        {
            if (IsRunningAsAdmin())
            {
                return true;
            }

            // 如果不是管理员，尝试以管理员权限重启
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = Application.ExecutablePath,
                    Verb = "runas", // 请求管理员权限
                    UseShellExecute = true
                };

                Process.Start(startInfo);
                Application.Exit();
                return false;
            }
            catch (Exception ex)
            {
                Logger.Error($"请求管理员权限失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 检查程序是否以管理员权限运行
        /// </summary>
        /// <returns>是否为管理员</returns>
        public static bool IsRunningAsAdmin()
        {
            try
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 重启系统
        /// </summary>
        /// <param name="delaySeconds">延迟秒数</param>
        /// <returns>是否成功</returns>
        public static bool RestartSystem(int delaySeconds)
        {
            try
            {
                if (!EnsureShutdownPrivilege())
                {
                    Logger.Warn("无法获取系统重启权限");
                    return false;
                }

                string arguments = $"/r /t {delaySeconds} /c \"系统需要重启以完成升级\"";
                Process.Start(new ProcessStartInfo("shutdown.exe", arguments)
                {
                    UseShellExecute = true,
                    Verb = "runas"
                });

                return true;
            }
            catch (Exception ex)
            {
                Logger.Error($"重启系统失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 获取系统关机权限
        /// </summary>
        private static bool EnsureShutdownPrivilege()
        {
            IntPtr tokenHandle = IntPtr.Zero;
            if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out tokenHandle))
            {
                return false;
            }

            TokPriv1Luid tp = new TokPriv1Luid();
            tp.Count = 1;
            if (!LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, out tp.Luid))
            {
                return false;
            }

            tp.Attr = SE_PRIVILEGE_ENABLED;
            if (!AdjustTokenPrivileges(tokenHandle, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 检查是否为64位系统
        /// </summary>
        public static bool Is64BitOperatingSystem()
        {
            if (IntPtr.Size == 8)
                return true;

            if (!IsWow64Process(Process.GetCurrentProcess().Handle, out bool isWow64))
                return false;

            return isWow64;
        }
    }
}
    